#!/usr/bin/evn python
#coding:utf-8
#-------------------------------------
#花一个月时间来研究这个代码，将里面的工作原理搞清楚
#起始时间：2010-10-01
#作者：Wyatt.Wang
#本代码是从FC第34期中来，是python编程中的第8部份
#-------------------------------------

import apsw  #apsw 是SQLite中的一个模块，在Ubuntu中，可在新立得中搜索然后安装
import string
import webbrowser #一个web的输出模块

class Cookbook:
    #pass
    def __init__(self):
        '''
        初始化库，设置全局变量connection,cursor，并链接到数所库
        '''
        #pass
        global connection
        global cursor
        self.totalcount = 0
        #connection = apsw.Connection('cookbook.db3')
        connection = apsw.Connection('cb.db3')
        cursor = connection.cursor()

    def PrintAllRecipes(self):
        '''
        打印数据库中的食谱数据。
        '''
        #pass
        print '%s %s %s %s' % ('Item'.ljust(5),'Name'.ljust(30),'Server'.ljust(20),'Source'.ljust(30))
        print '-'*80
        sql = 'SELECT * FROM Recipes'
        cntr = 0
        for x in cursor.execute(sql):
            cntr += 1
            print '%s %s %s %s' % (str(x[0]).ljust(5),x[1].ljust(30),x[2].ljust(20),x[3].ljust(30))
        print '-'*80
        self.totalcount = cntr

    def SearchForRecipe(self):
        pass
    def PrintSingleRecipe(self,which):
        pass
    def DeleteRecipe(self,which):
        pass
    def EnterNew(self):
        '''
        向数据库里添加新的食谱。
        '''
        ings = []
        recipename = ''
        recipesource= ''
        recipeserves = ''
        instructions = ''
        lastid = 0
        resp = raw_input('输入食谱名称 （为空时退出） ->')
        if resp != '': #不为空时继续下面程序。
            if string.find(resp,"'"):
                recipename = resp.replace("'","\'")
            else:
                recipename = resp
            print "食谱的名字是 %s"%recipename
            resp = raw_input('输入食谱所需的材料 ->')
            if string.find(resp,"'"):
                rescipesource = resp.replace("'","\'")
            else:
                recipesource = resp
            resp = raw_input('输入食谱所需步骤数 ->')
            if string.find(resp,"'"):
                rescipeserves = resp.replace("'","\'")
            else:
                recipeserves = resp
            print '现在可以输入食谱的制作步骤清单了。'
            cont = True
            while cont == True:
                ing = raw_input('输入内容 （输入"0"即退出）->')
                if ing != '0':
                    ings.append(ing)
                else:
                    cont = False
            resp = raw_input('Enter Instructions ->')
            instructions = resp
            print '~'*60
            print "Here's what we have so far"
            print "Title: %s" % recipename
            print "Source: %s"%recipesource
            print "Servers: %s"%recipeserves
            print "Ingredients:"
            for x in ings:
                print x
            print "Instructions: %s"%instructions
            print "~"*60
            resp = raw_input("OK to SAVE? (Y/n) ->")
            if string.upper(resp) != 'N':
                connection = apsw.Connection("cb.db3")
                cursor = connection.cursor()
                sql = 'INSERT INTO Recipes (name,servings,source) VALUES ("%s","%s","%s")'%(recipename,recipeserves,recipesource)
                cursor.execute(sql)
                sql = "SELECT last_insert_rowid()"
                cursor.execute(sql)
                for x in cursor.execute(sql):
                    lastid = [0]
                    print "last id = %s"%lastid
                for x in ings:
                    sql = 'INSERT INTO Ingredients (recipeID,ingredients) VALUES ("%s","%s")'%(lastid,x)
                    cursor.exectute(sql)

                sql = 'INSERT INTO Ingredients (recipeID,ingredients) VALUES ("%s","%s")'%(lastid,instructions)
                cursor.exectute(sql)
                print 'Done'
            else:
                print 'Save aborted'
        #pass
    def PrintOut(self,which):
        pass

def Menu():
    cbk = Cookbook() #初始化库
    loop = True
    while loop == True:
        print '='*60
        print '                 RECIP DATABASE'
        print '='*60
        print ' 1 - 显示所有食谱'
        print ' 2 - 搜索食谱'
        print ' 3 - 显示一个食谱'
        print ' 4 - 删除一个食谱'
        print ' 5 - 添加一个食谱'
        print ' 6 - 在浏览器中输出食谱'
        print ' 0 - 退出本程序'
        print '='*60
        sel = raw_input('输入你的选择 -> ')
        if sel == '1':
            #pass
            cbk.PrintAllRecipes()
            print 'Total Recipes - %s'%cbk.totalcount
            print '-'*60
            res = raw_input('Press A Key ->')
        elif sel == '2':
            pass
        elif sel == '3':
            pass
            #cbk.PrintAllRecipes()
        elif sel == '4':
            pass
            cbk.P
        elif sel == '5':
            pass 
        elif sel == '6':
            pass
        elif sel == '0':
            print '哈哈，既然你不想玩了，那就下次再见吧！'
            loop = False
        else:
            print '你所选的内容并非我们所有的，再次一次吧，不要整错了！'

if __name__ == '__main__':
    Menu()
